<template>
  <div class="form-single-fragment" style="position: relative;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" size="mini" label-position="right">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工作流程名称" prop="flowName">
            <el-input class="input-item" v-model="ruleForm.flowName" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属业务" prop="businessType">
            <el-cascader v-model="businesstypeId"
              ref="ref_business"
              :options="businesstypeTree"
              :props="businesstProps"
              :show-all-levels="false"
              @change="businessChange"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属阶段" prop="businessStage">
            <el-select v-model="ruleForm.businessStage" placeholder="请选择" @change="loadStagewWidgetData">
              <el-option label="商机阶段" :value="1"></el-option>
              <el-option label="立项阶段" :value="2"></el-option>
              <el-option label="合同阶段" :value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作流程" prop="entryId">
            <el-select v-model="ruleForm.entryId" placeholder="请选择" @change="flowEntryChange">
              <el-option v-for="(item,index) in flowEntrylist" :key="index"
              :label="item.processDefinitionName" :value="item.entryId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工作流程图" prop="entryId">
            <ProcessViewer ref="ProcessViewers" :style="{height: (getMainContextHeight - 260) + 'px'}"
              :xml="processXml"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="启用状态" prop="enabled">
            <el-radio-group v-model="ruleForm.enabled">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item style="padding: 20px 0;">
            <el-button size="mini" @click="onCancel(false)">取消</el-button>
            <el-button type="primary" size="mini" @click="submitForm()">保存</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { Workflow, Businesstype } from '@/api/business.js';
import ProcessViewer from '@/views/workflow/components/ProcessViewer.vue';
import { mapGetters } from 'vuex';
import { findTreeNodePath } from '@/utils';
export default {
  name: 'WorkflowAdd',
  components: {
    ProcessViewer
  },
  props: {
    workflowId: {
      default: undefined
    }
  },
  data () {
    return {
      loading: false,
      isShowloading: false,
      processXml: undefined,
      businessCode: '',
      businesstypeTree: [],
      businesstypeId: [],
      flowEntrylist: [],
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        checkStrictly: true
      },
      ruleForm: {
        flowName: '',
        businessType: '',
        businessStage: '',
        enabled: 1,
        entryId: ''
      },
      rules: {
        flowName: [{ required: true, message: '请输入', trigger: 'blur' }],
        businessType: [{ required: true, message: '请选择', trigger: 'change' }],
        businessStage: [{ required: true, message: '请选择', trigger: 'blur' }],
        enabled: [{ required: true, message: '请选择', trigger: 'change' }],
        entryId: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    };
  },
  created () {
    this.formInit();
  },
  computed: {
    isEdit () {
      return this.workflowId != null && this.workflowId !== '';
    },
    ...mapGetters(['getMainContextHeight'])
  },
  mounted () {

  },
  methods: {
    formInit () {
      let loadAllDatasource = [
        this.loadWorkflowDetail(),
        this.loadusinesstypeTree()
      ];
      Promise.all(loadAllDatasource).then(res => {
        if (!this.isEdit) return;
        this.businesstypeId = findTreeNodePath(this.businesstypeTree, this.ruleForm.businessType)
      }).catch(e => {
        console.log('e=' + JSON.stringify(e.toString()))
      });
    },
    /**
     * 工作流程详情
     */
    loadWorkflowDetail () {
      if (!this.isEdit) return;
      let params = {id: this.workflowId}
      return new Promise((resolve, reject) => {
        Workflow.detail(this, params).then(res => {
          this.ruleForm = res.data
          this.processXml = res.data.bpmnXml
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.ProcessViewers.processReZoom()
            });
          }, 500)
          this.loadflowWidgetData()
          this.$forceUpdate()
          resolve()
        }).catch(e => {
          console.log('e=' + JSON.stringify(e))
          reject(e);
        });
      });
    },
    loadStagewWidgetData () {
      this.ruleForm.entryId = ''
      this.loadflowWidgetData()
    },
    /**
     * 工作流程列表
     */
    loadflowWidgetData () {
      if (!this.ruleForm.businessStage || !this.ruleForm.businessType) return;
      let params = {
        businessStage: this.ruleForm.businessStage,
        businessType: this.ruleForm.businessType
      }
      return new Promise((resolve, reject) => {
        Workflow.flowList(this, params).then(res => {
          this.flowEntrylist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    flowEntryChange (value) {
      this.flowEntrylist.forEach(item => {
        if (item.entryId === value) {
          this.processXml = item.bpmnXml
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.ProcessViewers.processReZoom()
            });
          }, 500)
        }
      })
    },
    /**
     * 业务类型信息表树形列表
     */
    loadusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this).then(res => {
          this.businesstypeTree = res.data
          resolve();
        }).catch(e => {
          reject(e);
        });
      });
    },
    businessChange () {
      let info = this.businesstypeId
      let length = info.length - 1
      this.ruleForm.businessType = info[length]
      this.loadflowWidgetData()
    },
    /**
     * 提交表单
     */
    submitForm () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          let params = {
            businessFlow: this.ruleForm
          };
          if (this.isEdit) { // 修改
            return new Promise((resolve, reject) => {
              Workflow.update(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '修改成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          } else { // 添加
            return new Promise((resolve, reject) => {
              Workflow.add(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '添加成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    }
  }
}
</script>

<style scoped>
h3{border-bottom: 1px solid #E9E9EB;padding: 0 0 10px;}
.table_container{margin: 10px 0;}
.form-single-info{display: flex;justify-content: center;}
.el-form-info{box-shadow: 0 0 10px rgba(0,0,0,0.05);padding: 20px;}
.el-form-info strong{margin: 0 10px;}
.el-form-info .el-time-picker{width: 100%;}
</style>
